//
//  BVMyOrderTableViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/13.
//  Copyright (c) 2015年 叶思超. All rights reserved.

#import "BVMyOrderViewController.h"
#import "BVConst.h"
#import "BVMyOrderCell.h"
#import "BVMyDetailOrderViewController.h"
#import "HttpTool.h"
#import "BVMyOrder.h"
#import "MJExtension.h"
#import "BVNextOrderViewController.h"
#import "MBProgressHUD+MJ.h"
@interface BVMyOrderViewController () <UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate,OrderCellDelegate>
/**
 *  创建tableview
 */
@property (nonatomic, strong) UITableView *tableView;
/**
 *  存放所有订单信息
 */
@property (nonatomic, strong) NSMutableArray *orders;
/**
 *  蒙板
 */
@property (nonatomic, strong) UIButton *coverButton;
/**
 *  拨打电话
 */
@property (nonatomic, strong) UIWebView *phoneCallWebView;

/**
 * 当前选中的order
 */
@property (nonatomic,weak) BVMyOrder * currentOrder;
@end

@implementation BVMyOrderViewController

- (NSMutableArray *)orders {
    if (!_orders) {
        _orders = [NSMutableArray array];
    }
    return _orders;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置导航栏
    [self setupNav];
    
    // 创建tableview
    [self setupTableView];
    
    // 获取我的订单
    [self loadMyOrderData];
}

#pragma mark -- 获取我的订单
- (void)loadMyOrderData {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/getMyOrderListById", Path];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults    = [NSUserDefaults standardUserDefaults];
    NSDictionary * userinfo =[defaults objectForKey:@"USERINFO"];
    NSString *user_id = userinfo[@"id"];


    if (user_id != nil) {
        params[@"user_id"] = user_id;
        SHOWLOADING
        [HttpTool get:url params:params success:^(id responseObj) {
            HIDELOADING
            if ([responseObj[@"code"] isEqualToString:@"1"]) {
                NSArray *array = [BVMyOrder objectArrayWithKeyValuesArray:responseObj[@"data"]];
                [self.orders addObjectsFromArray:array];
                
                [self.tableView reloadData];
            } else {
                ERROR(@"没有订单信息");
            }
        } failure:^(NSError *error) {
            NETWORKINGERROR
        }];
    }
}

#pragma mark -- 创建tableview
- (void)setupTableView {
    self.tableView  = [[UITableView alloc] init];
    self.tableView.frame  = CGRectMake(0, 64, BVScreenW, BVScreenH - 64 - 49);
    self.tableView.frame  = CGRectMake(0, 64, BVScreenW, BVScreenH - 64);
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource  = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 160;
    [self.view addSubview:self.tableView];
}
#pragma mark OrderCellDelegate
- (void)orderCell:(BVMyOrderCell *)cell deleteOrder:(BVMyOrder *)order{
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/doDelOrderById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"order_id"] = order.order_id;
    
    [HttpTool get:url params:params success:^(id responseObj) {
        
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            
            MBProgressHUD * hub = [MBProgressHUD showMessage:@"删除订单成功" toView:self.view];
            [hub hide:YES afterDelay:0.3f];
            [self.orders removeObject:order];
            [self.tableView reloadData];
        }else{
            
            ERROR(@"订单删除失败");
           
        }
        
    } failure:^(NSError *error) {
       NETWORKINGERROR
    }];
}


- (void)orderCell:(BVMyOrderCell *)cell confirmOrder:(BVMyOrder *)order{
    self.currentOrder = order;
    // 弹出提示框
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"支付宝", @"微信支付",nil];
    [actionSheet showInView:self.tableView];
}


- (void)orderCell:(BVMyOrderCell *)cell nextOrder:(BVMyOrder *)order{

    BVNextOrderViewController *nextOrderVC = [[BVNextOrderViewController alloc] init];
    nextOrderVC.myOrder = order;
    ROOTNAVPUSH(nextOrderVC, YES);

}
#warning querenshouhuo!!!
//取消确认收货
- (void)orderCell:(BVMyOrderCell *)cell confirmReceive:(BVMyOrder *)order{
//    // 拼接路径
//    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/doConfirmReceiptById", Path];
//
//    // 拼接参数
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//
//    params[@"order_id"] = order.order_id;
//    
//    [HttpTool get:url params:params success:^(id responseObj) {
//        
//        if ([responseObj[@"code"] isEqualToString:@"1"]) {
//            
//            MBProgressHUD * hub = [MBProgressHUD showMessage:@"确认收货成功" toView:self.view];
//            [hub hide:YES afterDelay:0.3f];
//            order.status = @"2";
//            NSIndexPath * indexpath = [self.tableView indexPathForCell:cell];
//            [self.tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationNone];
//        }else{
//            ERROR(@"确认收货失败");
//        }
//        
//    } failure:^(NSError *error) {
//        NETWORKINGERROR
//    }];
}


- (void)orderCell:(BVMyOrderCell *)cell cancelBtn:(BVMyOrder *)order{
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/cancelOrder", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"order_id"] = order.order_id;
    
    [HttpTool get:url params:params success:^(id responseObj) {
        
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            
            MBProgressHUD * hub = [MBProgressHUD showMessage:@"取消订单成功" toView:self.view];
            [hub hide:YES afterDelay:0.3f];
            
            NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/doDelOrderById", Path];
            
            // 拼接参数
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"order_id"] = order.order_id;
            
            [HttpTool get:url params:params success:^(id responseObj) {
                
                if ([responseObj[@"code"] isEqualToString:@"1"]) {
                    
                    MBProgressHUD * hub = [MBProgressHUD showMessage:@"取消订单成功" toView:self.view];
                    [hub hide:YES afterDelay:0.3f];
                    [self.orders removeObject:order];
                    [self.tableView reloadData];
                }else{
                    
                    ERROR(@"订单删除失败");
                    
                }
                
            } failure:^(NSError *error) {
                NETWORKINGERROR
            }];

            
            [self.tableView reloadData];
        }else{
            
            ERROR(@"订单删除失败");
            
        }
        
    } failure:^(NSError *error) {
        NETWORKINGERROR
    }];

}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.orders.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //创建cell
    BVMyOrderCell *cell = [BVMyOrderCell cell];
    cell.delegate = self;
    // 传递模型
    cell.myOrder = self.orders[indexPath.row];

    return cell;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BVMyDetailOrderViewController *myDetailOrderVC = [[BVMyDetailOrderViewController alloc] init];
    myDetailOrderVC.myOrder = self.orders[indexPath.row];
    ROOTNAVPUSH(myDetailOrderVC, YES);
}

#pragma mark -- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    BVPayManager * manager = [BVPayManager manager];
    if(buttonIndex == 0){
        [manager pay:PayTypeAliPay orderNum:self.currentOrder.ordernum finishBlock:^{
            
            [BVShopCart deleteAllShopFromCart];
            [self.orders removeAllObjects];
            [self loadMyOrderData];
        } successBlock:^{
            
        } faileBlock:^{
            
        }];
    }else if(buttonIndex == 1){
        [manager pay:PayTypeWX orderNum:self.currentOrder.ordernum finishBlock:^{
            [BVShopCart deleteAllShopFromCart];
            [self.orders removeAllObjects];
            [self loadMyOrderData];
        } successBlock:^{
            
        } faileBlock:^{
            
        }];
    }
}

#pragma mark -- 取消打电话
- (void)cancelButtonClick {
    [self.coverButton removeFromSuperview];
}

/**
 *  打电话
 */
- (void)phoneButtonClick {
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",@"0531-58192080"]];
    if ( !_phoneCallWebView ) {
        _phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    }
    [_phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.title  = @"我的订单";
    self.navigationController.navigationBar.barTintColor  = BVBaseOrangeColor;
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem   = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"wddd_tel"] style:UIBarButtonItemStyleDone target:self action:@selector(phoneButtonClick)];
}
#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP;
}

@end
